﻿using Microsoft.Xaml.Interactivity;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace DPE.TED.OCAF.Win8SampleClient.UI_Helpers
{
    public class ScrollIntoView : DependencyObject, IBehavior
    {
        public DependencyObject AssociatedObject
        {
            get;
            private set;
        }

        public void Attach(DependencyObject associatedObject)
        {
 	        ListView lv = associatedObject as ListView;
            if (lv != null)
            {
                AssociatedObject = lv;
                lv.SelectionChanged += lv_SelectionChanged;
            }
        }

        private void lv_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
 	        ListView lv = this.AssociatedObject as ListView;
            if (lv != null)
            {
                lv.ScrollIntoView(lv.SelectedItem);
            }
        }

        public void Detach()
        {
 	        ListView lv = this.AssociatedObject as ListView;
            if (lv != null)
            {
                lv.SelectionChanged -= lv_SelectionChanged;
            }
        }
    }
}
